import * as API_NetworkAuth from '../../../api/networkAuth'
import * as API_Article from '../../../api/article'
import * as API_Passport from '../../../api/passport'
import * as API_Trade from '../../../api/trade'
import * as API_Distribution from '../../../api/distribution'
let WxParse = require('../../../lib/wxParse/wxParse')
Page({
  data:{
    registerForm:{
      mobile:'',
      invitationCode:'',
      code:'',
    },
    uuid:'',
    initTip: '发送验证码',
    endTip: '重新获取',
    sufTip: '秒后重新获取',
    count_time: 60,
    disabled: false,
    interval:null,
    message: '',
    showAgreement: false,//是否显示注册协议
    agreement: '', // 注册协议
    agreed: false, // 同意注册协议
    agreementCb:true,
    inviteCode:''
  },
  onLoad: function (options) {
    wx.login({
      success: function (res) {
        var code = res.code;
        // 请求后台获取session_key
        wx.request({
          url: 'https://apibuyer.oupinguoji.cn/passport/mini-program/sessionKey',
          method: "get",
          data: {code,number:1} ,
          success: function (res) {
            wx.setStorageSync('open_id', res.data.openid)
            wx.setStorageSync('session_key', res.data.session_key)
          }
        })
      }
    })
    const uuid = wx.getStorageSync('uuid')
    let qrId=wx.getStorageSync('qrId')
    let inviteCode = wx.getStorageSync('inviteCode')
    this.setData({ uuid: uuid })
    if(qrId){
      this.setData({"registerForm.invitationCode": qrId})
    }
    if(inviteCode){
      this.setData({ "registerForm.invitationCode": inviteCode })
    }
    /* 分享进入  填入推荐人*/
    if (options.su) {
      this.setData({ su: options.su })
      API_NetworkAuth.accessShortLink({ su: options.su, uuid: wx.getStorageSync('uuid') }).then(res => {
        this.setData({ "registerForm.invitationCode": res.mobile, isReferrerMobile: true })
      })
    }

    this.loadPage();
  },
  inputCode(e){
    this.setData({'registerForm.invitationCode':e.detail.value})
  },
  goRegister(){
    wx.navigateTo({
      url: '/pages/auth/otherRegister/otherRegister',
    })
  },
  goLogin(){
    wx.navigateTo({
      url: '/pages/auth/otherLogin/otherLogin',
    })    
  },
  // 表单双向绑定
  // syncMobile(e){this.setData({ "registerForm.mobile": e.detail.value })},
  // syncInvitationCode(e){this.setData({ "registerForm.invitationCode": e.detail.value })},
  // syncCode(e){this.setData({ "form.code": e.detail.value })},

  //下一步
  // handleNextStep() {
  //   if(!this.data.agreementCb){
  //     wx.showToast({
  //       title: '请勾选注册协议',
  //       icon:'none'
  //     })
  //   }
  //   const { mobile, invitationCode } = this.data.registerForm
  //   if (!mobile) {
  //     wx.showToast({ title: '请输入手机号！', icon: 'none' })
  //     return false
  //   }
  //   this.handleConfirmRegister();
  // },
  //立即注册
  // handleConfirmRegister() {
    
  //   const { mobile, invitationCode/*,  password, rep_password */ } = this.data.registerForm
  //   // 获取用户信息
  //   wx.getUserInfo({
  //     lang: 'zh_CN',
  //     success: (res) => {
  //       const userInfo = res.userInfo
  //       const params = {
  //         nick_name: userInfo.nickName,
  //         face: userInfo.avatarUrl,
  //         sex: userInfo.gender === 1 ? 1 : 0,
  //         mobile: mobile,
  //         password: '000000',
  //         invitationCode
  //       }
  //       // 注册绑定
  //       API_NetworkAuth.registerBindConnect(this.data.uuid, params).then((res) => {
  //         const { access_token, refresh_token, uid } = res
  //         wx.setStorageSync('access_token', access_token)
  //         wx.setStorageSync('refresh_token', refresh_token)
  //         wx.setStorageSync('uid', uid)
  //         this.setData({ su: null });
  //         API_NetworkAuth.getUserInfo().then((response) => {
  //           wx.setStorageSync('user', response)
  //           wx.switchTab({ url: '/pages/home/home' })
  //         })
  //       })
  //     }
  //   })
  // },
  loadPage() {
    // 如果未授权 进行授权
    // if (wx.getStorageSync('wxauth')) {
    //   this.setData({ showWxAuth: true })
    // } else {
    //   this.setData({ showWxAuth: false })
    // }
    // 获取用户协议
    API_Article.getArticleByPosition('REGISTRATION_AGREEMENT').then(response => {
      WxParse.wxParse('agreement', 'html', response.content, this)
    })
  },
  //同意协议
  handleAgreement(e) {
    const agreed = JSON.parse(e.currentTarget.dataset.agreed)
    if (!agreed) {
      wx.switchTab({ url: '/pages/home/home' })
    } else {
      this.setData({
        showAgreement: false,
        agreed: agreed
      })
    }
  },
  // 授权手机号
  getPhoneNumber(e){
    var self = this;
    // 允许后执行
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      var params = {
          encrypted_data : e.detail.encryptedData,
          iv: e.detail.iv,
          session_key : wx.getStorageSync('session_key')
      }
      wx.request({
        url: 'https://apibuyer.oupinguoji.cn/passport/mini-program/phone/decrypt',
        data: params,
        method: 'POST',
        success: function (res) {
          self.setData({
            'registerForm.mobile': res.data.phoneNumber
          })
          const { mobile, invitationCode } = self.data.registerForm
          //检测手机号
        API_Passport.checkMobileRepeat(mobile).then(response=>{
          if(!response.exist){
            console.log('1')
          // 获取用户信息
          wx.getUserInfo({
            lang: 'zh_CN',
            success: (res) => {
              const userInfo = res.userInfo
              //填写邀请码
              if(self.data.registerForm.invitationCode){
                //检测邀请码
                API_Passport.checkMobileRepeat(self.data.registerForm.invitationCode).then(res=>{
                  //邀请人不存在
                  if(!res.exist){
                    wx.showToast({
                      title: '邀请码不存在！',
                      icon: 'none'
                    })
                  }
                  //邀请人存在
                  else{
                    const params = {
                      nick_name: userInfo.nickName,
                      face: userInfo.avatarUrl,
                      sex: userInfo.gender === 1 ? 1 : 0,
                      mobile: mobile,
                      password: '000000',
                      referrer_mobile:self.data.registerForm.invitationCode
                    }
              // 注册绑定
              API_NetworkAuth.registerBindConnect(self.data.uuid, params).then((res) => {
                const { access_token, refresh_token, uid } = res
                wx.setStorageSync('access_token', access_token)
                wx.setStorageSync('refresh_token', refresh_token)
                wx.setStorageSync('uid', uid)
                self.setData({ su: null });
                API_NetworkAuth.getUserInfo().then((response) => {
                  wx.setStorageSync('user', response)
                  wx.navigateBack({
                    delta: 1
                  })
                })
              })                    
                  }
                })
              }
              //未填写邀请码
              else{
                const params = {
                  nick_name: userInfo.nickName,
                  face: userInfo.avatarUrl,
                  sex: userInfo.gender === 1 ? 1 : 0,
                  mobile: mobile,
                  password: '000000',
                  referrer_mobile:''
                }
              // 注册绑定
              API_NetworkAuth.registerBindConnect(self.data.uuid, params).then((res) => {
                const { access_token, refresh_token, uid } = res
                wx.setStorageSync('access_token', access_token)
                wx.setStorageSync('refresh_token', refresh_token)
                wx.setStorageSync('uid', uid)
                self.setData({ su: null });
                API_NetworkAuth.getUserInfo().then((response) => {
                  wx.setStorageSync('user', response)
                  wx.navigateBack({
                    delta: 1
                  })
                })
              })
              }
              // const params = {
              //   nick_name: userInfo.nickName,
              //   face: userInfo.avatarUrl,
              //   sex: userInfo.gender === 1 ? 1 : 0,
              //   mobile: mobile,
              //   password: '000000',
              //   referrer_mobile:self.data.registerForm.invitationCode
              // }
              // 注册绑定
              // API_NetworkAuth.registerBindConnect(self.data.uuid, params).then((res) => {
              //   const { access_token, refresh_token, uid } = res
              //   wx.setStorageSync('access_token', access_token)
              //   wx.setStorageSync('refresh_token', refresh_token)
              //   wx.setStorageSync('uid', uid)
              //   self.setData({ su: null });
              //   API_NetworkAuth.getUserInfo().then((response) => {
              //     wx.setStorageSync('user', response)
              //     wx.navigateBack({
              //       delta: 1
              //     })
              //   })
              // })
            }
          })
        }
        else{
          console.log('2')
          const params={mobile:mobile}
          API_NetworkAuth.loginBymini(wx.getStorageSync('uuid'),params).then(response => {
            console.log(response)
            if(response.result=="existed"){
              wx.login({
                success(res){
                  const param={code:res.code,number:1,uuid:wx.getStorageSync('uuid')}
                  API_NetworkAuth.loginByAuto(param).then(res=>{
                    wx.showToast({
                      title: '登陆成功',
                      icon: 'none'
                    })
                    wx.setStorageSync('access_token', res.access_token)
                    wx.setStorageSync('refresh_token', res.refresh_token)
                    wx.setStorageSync('uid', res.uid)
                                // 获取用户信息
                API_NetworkAuth.getUserInfo().then(res => {
                  wx.setStorageSync('user', res)
                })
                wx.navigateBack({
                  delta: 1
                })
                  })
                }
              })
            }
            else{
            wx.showToast({
              title: '登陆成功',
            })
            wx.setStorageSync('access_token', response.access_token)
            wx.setStorageSync('refresh_token', response.refresh_token)
            wx.setStorageSync('uid', response.uid)
            // 获取用户信息
            API_NetworkAuth.getUserInfo().then(res => {
              wx.setStorageSync('user', res)
            })
            wx.navigateBack({
              delta: 1
            })
          }
          })
        }
      })
        



        },
        fail: function (err) {
          console.log(err)
        }
      })
    }
  },
  // 显示注册协议
  showagreement(){
    this.setData({showAgreement:true})
  },
  // 
  toLogin(){
    wx.navigateTo({
      url: '/pages/auth/login/login',
    })
  }
})